package group.rober.saber.jdbc;

import group.rober.saber.kit.ValidateKit;
import group.rober.saber.lang.DataBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;

/**
 * 自定义SQL字段和Map属性的映射关系
 * Created by tisir<yangsong158@qq.com> on 2017-05-30
 */
public class DataBoxByMapRowMapper implements RowMapper<DataBox> {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    private Map<Integer, String> fieldsMap;

    public DataBoxByMapRowMapper(Map<Integer, String> fieldsMap) {
        this.fieldsMap = fieldsMap;
        initialize();
    }

    protected void initialize() {
        ValidateKit.notNull(fieldsMap, "fieldsMap Null is not allowed");
    }

    protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
        return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
    }

    protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
        return JdbcUtils.getResultSetValue(rs, index);
    }

    public DataBox mapRow(ResultSet rs, final int rowNum) throws SQLException {
//        ResultSetMetaData metaData = rs.getMetaData();
//        int columnCount = metaData.getColumnCount();
        DataBox mapBox = new DataBox();

        Iterator<Integer> iterator = fieldsMap.keySet().iterator();
        while (iterator.hasNext()) {
            Integer column = iterator.next();
            String propertyName = fieldsMap.get(column);
            Object value = getColumnValue(rs, column);
            mapBox.put(propertyName,value);
        }

        return mapBox;
    }
}
